import React, {Suspense, useEffect, useLayoutEffect, useReducer, useState} from 'react';
import {Route, Routes, useNavigate} from "react-router-dom";
import {
    GlobalStateContext,
    GlobalDispatchContext,
    initialState,
    reducer,
} from "./redux/globalContext";
import { Skeleton} from "antd";
import routerConf from "@/router/routerConf";
import mRouter, {mlist} from "@/router/mRouter";
import LoginPage from "./pages/Login"
import Layout from "@/cms/Layout/index"
import jsCookie from "js-cookie";
import getMenuList from "@/router/getMenuList";
import toAuth from "@/pages/wx/auth";

function RouterDOM({routerList}) {

    return <Suspense fallback={<>
        <Skeleton active/>
        <Skeleton active/>
        <Skeleton active/>
        <Skeleton active/>
    </>}>
        <Routes>
            {
                routerList().map((item) => <Route key={item.path} path={item.path} element={<item.ele/>}/>)
            }
        </Routes>
    </Suspense>
}
function App() {
    const navigate = useNavigate();
    const [state, dispatch] = useReducer(reducer, initialState);
    const [isAdmin,setIsAdmin] = useState(true)
    useEffect(()=>{
        let _isAdmin ;
        if(location.pathname.includes("/ouyu/")){
            _isAdmin=true
        }else{
            _isAdmin=false
        }
        setIsAdmin(_isAdmin)
        const info = JSON.parse(jsCookie.get("info")||"{}");
        window.company_id=info.company_id
        const pathname = location.pathname
        // 公众号页面未登录 跳转到登录页面
        if (pathname.includes("/wx/")){
            // toAuth(location.href)
        }else{
            // 后台没登录 跳转登录页面
            if (info.expire === undefined || info.expire<new Date().valueOf()){
                navigate("/ouyu/login")
            }else if(pathname.includes("/ouyu/login")){
                if (getMenuList()[0]){
                    navigate(getMenuList()[0].path)
                }
            }
        }


    },[navigate])
    useEffect(()=>{
        const title = mlist.find(item=>item.path === location.pathname)?.label
        if (title){
            document.title = title
        }
    },[location.pathname])

    return (
        <GlobalStateContext.Provider value={state}>
            <GlobalDispatchContext.Provider value={dispatch}>
                <div style={{width:"100vw",height:"100vh",overflow:"hidden"}}>
                    <Routes>
                        <Route path={"/ouyu/login"} element={<LoginPage />}/>
                    </Routes>
                    {
                        isAdmin?<Layout>
                            <RouterDOM routerList={routerConf} />
                        </Layout>:
                            <RouterDOM routerList={mRouter}/>
                    }

                </div>

            </GlobalDispatchContext.Provider>
        </GlobalStateContext.Provider>
    );
}

export default App;
